<template>
    <view class="page-box">
        <header class="header"></header>
        <view class="section">
            <view class="title">QCR识别：</view>
            <view class="id-card column rowCenter verCenter" @click="chooseImageChange()">
                <text class="iconfont icon-a-tubiaochangyongsousuo1"></text>
                <text class="tt">上传身份证</text>
            </view>
            <view class="desc row rowCenter verCenter">*仅用于识别辅助填写</view>
            <view class="input-wrap">
                <view class="input-box">
                    <view class="title required">姓名：</view>
                    <input type="text" placeholder="请输入姓名" class="uni-input" placeholder-style="color: #6E767A;" v-model="form.id_card_name" @blur="handleBlur(form.id_card_name,form.mobile)" />
                </view>
                <view class="input-box">
                    <view class="title required">身份证：</view>
                    <input type="idcard" placeholder="请输入身份证" class="uni-input" placeholder-style="color: #6E767A;" v-model="form.id_card" />
                </view>
                <view class="input-box">
                    <view class="title required">手机号：</view>
                    <input type="tel" inputmode="tel" placeholder="请输入手机号" class="uni-input" placeholder-style="color: #6E767A;" v-model="form.mobile" @blur="handleBlur(form.id_card_name,form.mobile)" />
                </view>
                <view class="input-box">
                    <view class="title required">邮箱：</view>
                    <input type="text" placeholder="请输入接收邮箱" class="uni-input" placeholder-style="color: #6E767A;" v-model="form.email" />
                </view>
            </view>
        </view>
        <view class="btn row rowCenter verCenter" @click="submitUserData" :class="{disabled:is_disabled}">提交</view>
        <!-- 支付弹窗 -->
        <uni-popup ref="popup" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column rowCenter verCenter">
                    <view class="ico">
                        <image src="../../static/pay.png" mode="aspectFill"></image>
                    </view>
                    <view class="row">
                        <text class="t2">请支付</text>
                        <text class="t3">{{addCreditPayOrderForm.amount}}元</text>
                        <template v-if="form.req_type == 1">
                            <text class="t2">开启您的用户画像</text>
                        </template>
                        <template v-else-if="form.req_type == 2">
                            <text class="t2">开启您的人法查询</text>
                        </template>
                        <template v-else-if="form.req_type == 3">
                            <text class="t2">开启您的征信授权</text>
                        </template>
                    </view>
                    <view class="price row rowCenter verCenter">￥{{addCreditPayOrderForm.amount}}</view>
                    <view class="pay row rowCenter verCenter" @click="addCreditPayOrder()">去支付</view>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';

    export default {
        data() {
            return {
                is_disabled: false, //二要素验证
                addCreditPayOrderForm: {
                    id: '',
                    amount: 0
                },
                form: {
                    id_card_name: '',
                    id_card: '',
                    id_card_url: '',
                    mobile: '',
                    req_type: '', //申请类型
                    email: ''
                }
            };
        },
        onLoad(options) {
            this.form.req_type = options.req_type || '';
            if (this.form.req_type == 1) {
                uni.setNavigationBarTitle({
                    title: '用户画像'
                })
            } else if (this.form.req_type == 2) {
                uni.setNavigationBarTitle({
                    title: '人法查询'
                })
            } else if (this.form.req_type == 3) {
                uni.setNavigationBarTitle({
                    title: '征信授权'
                })
            }
        },
        methods: {
            /**
             * 打开弹窗
             */
            open() {
                this.$refs.popup.open();
            },
            /**
             * 关闭弹窗
             */
            close() {
                this.$refs.popup.close();
            },
            handleBlur(realname, mobile) {
                if (mobile && realname) {
                    this.twoElementsRecognition(realname, mobile);
                }
            },
            /**
             * 二要素核验接口
             */
            twoElementsRecognition(name, mobile) {
                this.request(API.twoElementsRecognition, 'POST', { name: name, mobile: mobile }, true).then(res => {
                    if (res.code === 0) {
                        this.is_disabled = false;
                    } else {
                        this.is_disabled = true;
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 识别图片
             */
            chooseImageChange() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '识别中...'
                        });

                        // 获取选择的图片路径数组
                        const imagePath = chooseImageRes.tempFilePaths[0]; // 获取选中的图片路径

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: imagePath,
                            name: 'file',
                            formData: {
                                'source': 'appUser',
                                'isNoCheck_12345qwert': '12345_qwert', //去掉防刷验证
                                'is_use_ocr': 3 //是否使用图片识别，0-否，1-是
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    this.form.id_card_name = data.data.name;
                                    this.form.id_card = data.data.idNumber;
                                    this.form.id_card_url = data.data.file_url;
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 提交用户资料
             */
            submitUserData() {
                if (!this.form.id_card_name) {
                    uni.showToast({
                        title: '请输入姓名',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.id_card) {
                    uni.showToast({
                        title: '请输入身份证',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.mobile) {
                    uni.showToast({
                        title: '请输入手机号',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.email) {
                    uni.showToast({
                        title: '请输入邮箱',
                        icon: 'none'
                    });
                    return false;
                }
                if (this.is_disabled) {
                    uni.showToast({
                        title: '请输入真实姓名和手机号',
                        icon: 'none'
                    });
                    return false;
                }
                this.request(API.submitUserData, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        this.addCreditPayOrderForm.id = res.data.id;
                        this.addCreditPayOrderForm.amount = res.data.amount;
                        this.open();
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 添加信用支付订单
             */
            addCreditPayOrder() {
                this.request(API.addCreditPayOrder, 'POST', this.addCreditPayOrderForm, true).then(res => {
                    if (res.code === 0) {
                        this.initWeixinPay(res.data, res.data.pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 初始化微信支付
             * @param {Object} payParams 支付参数
             * @param {String} pay_id 支付ID
             */
            initWeixinPay(payParams, pay_id) {
                const onBridgeReady = () => {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                            this.close();
                            // 支付成功，开始轮询支付结果
                            this.startPollingPayResult(pay_id);
                        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
                            // 用户取消支付
                            uni.showToast({
                                title: '支付已取消',
                                icon: 'none'
                            });
                        } else {
                            // 其他情况，可能是支付失败或未知错误
                            uni.showToast({
                                title: '支付失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                };

                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady();
                }
            },
            /**
             * 开始轮询支付结果
             * @param {String} pay_id 支付ID
             */
            startPollingPayResult(pay_id) {
                let pollCount = 0;
                const maxPollCount = 10;
                const pollInterval = 1000; // 轮询间隔时间，单位毫秒

                // 使用 Promise 和 async/await 优化轮询逻辑
                const pollPayResult = async () => {
                    while (pollCount < maxPollCount) {
                        // 等待一段时间后再查询，避免立即查询
                        await new Promise(resolve => setTimeout(resolve, pollInterval));

                        try {
                            const result = await this.getCreditPayOrder(pay_id);
                            if (result.success) {
                                // 支付成功，结束轮询
                                return true;
                            }
                        } catch (error) {
                            console.error('查询支付结果出错:', error);
                        }

                        pollCount++;
                    }
                    // 达到最大轮询次数，仍未成功
                    return false;
                };

                // 开始轮询
                pollPayResult().then(success => {
                    if (success) {
                        console.log('支付成功');
                        // 可以在这里添加支付成功后的逻辑
                    } else {
                        console.log('支付结果查询超时');
                        // 可以在这里添加查询超时的处理逻辑
                    }
                });
            },
            /**
             * 支付成功后定时任务查询支付结果
             * @param {Object} pay_id
             */
            getCreditPayOrder(pay_id) {
                this.request(API.getCreditPayOrder, 'GET', { id: pay_id }, false).then(res => {
                    if (res.code === 0 && res.data.pay_status == 1) {
                        this.close();
                        uni.reLaunch({
                            url: '/pages/index/success?req_type=' + this.form.req_type
                        });
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/index/creditInquiry.scss';
</style>